from flask import Flask, render_template, request,session,redirect,jsonify
import json
from . import common
import os
from frameworks.cores.Config import *
from frameworks.utils.JsonResult2 import *
from frameworks.cores.LoadClass import *

basepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)
from flask_session import Session

jsonResult = JsonResult2()

loader = LoadClass()

@common.route('/groups')
def groups():
    title = request.args.get("title","")
    # 查询用户信息并展示
    return render_template(
        'groups.html',
        title = title,
        groupname = request.args.get("groupname","")
    )

@common.route('/select_group')
def select_group():
    # 查询用户信息并展示
    return render_template('dicts/select_group.html')

@common.route('/shubiao')
def shubiao():
    # 查询用户信息并展示
    return render_template('dicts/shubiao.html')

def build_tree(data,parent_id):
    '''生成树菜单的数据
    :param data: 数据
    :param parent_id: 父级id
    :return:
    '''
    tree = []
    for row in data:
        if row['parent_id'] == parent_id:
            child = build_tree(data, row['id'])
            row['children'] = []
            if child:
                row['children'] += child
            tree.append(row)
    return tree

@common.route('/get_class')
def get_class():
    categorys = loader.load("controller.ClassController", "ClassController", {
        "func": "getData",
        "model": "question_group"
    })
    list = []
    for row in categorys:
        data = dict(id=row["id"], parent_id=row["parent_id"], title=row["class_name"])
        list.append(data)
    data = build_tree(list, 0)
    return jsonify({'code': 0, 'msg': '获取节点数据成功', 'data': data})


@common.route('/add_area',methods=['post'])
def add_area():
    data = json.loads(request.form.get('form_data'))
    area_name = data['area_name']
    add_obj = loader.load("controller.ClassController", "ClassController", {
        "func": "add",
        "data": {"class_name":area_name,"parent_id":0},
        "model": "question_group"
    })
    try:
        return jsonify({'code': 0, 'msg': '添加顶级节点成功'})
    except Exception as e:
        return jsonify({'code': e, 'msg': '添加失败，请重试'})

# 添加节点
@common.route('/add_class',methods=['post'])
def add_class():
    parent_id = request.values.get('parent_id')
    title = request.values.get('title')
    class_name = loader.load("controller.ClassController", "ClassController", {
        "func": "getDataByParams",
        "data": {"class_name":title,"parent_id":parent_id},
        "model": "question_group"
    })
    title_d = []
    for class_n in class_name:
        class_name = class_n.class_name
        title_d.append(class_name)
    if title in title_d:  # 判断“未命名”是否已存在
        class_obj = loader.load("controller.ClassController", "ClassController", {
            "func": "getDataByParams",
            "data": {"class_name":title},
            "model": "question_group"
        })
        class_id = class_obj[0].id
        return jsonify({'code': 1, 'msg': '你添加的节点 "未命名" 还未修改名称','id':class_id})
    try:
        add_obj = loader.load("controller.ClassController", "ClassController", {
            "func": "add",
            "data": {"class_name":title,"parent_id":parent_id},
            "model": "question_group"
        })
        return jsonify({'code': 0, 'msg': '添加节点 “未命名” 成功，请修改节点名称'})
    except Exception as e:
        return jsonify({'code': e,'msg':'添加失败，请重试'})

# 修改节点
@common.route('/edit_class',methods=['post'])
def edit_class():
    class_id = request.values.get('class_id')
    title = request.values.get('title')
    try:
        edit_obj = loader.load("controller.ClassController", "ClassController", {
            "func": "update",
            "data": {"class_name": title, "id": class_id},
            "model": "question_group"
        })
        return jsonify({'code': 0, 'msg': '修改节点成功'})
    except Exception as e:
        return jsonify({'code': e, 'msg': '修改失败，请重试'})

# 删除节点
@common.route('/del_class',methods=['post'])
def del_class():
    class_id = request.values.get('class_id')
    try:
        del_obj = loader.load("controller.ClassController", "ClassController", {
            "func": "delete",
            "data": {"id": class_id},
            "model": "question_group"
        })
        return jsonify({'code': 0, 'msg': '删除节点成功'})
    except Exception as e:
        return jsonify({'code': e, 'msg': '删除失败，请重试'})
